package com.mocha;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;

/**
 * @author songkui
 * @since 2024/3/26 9:21
 */
@Getter
@Slf4j
public class SocketClient {


    private final static String url = "http://10.3.15.3:18000";
//    private final static String url = "ws://localhost:9092";
    private final static String park = "jiangan"; // 园区编号

    private String userId;
    private String token;

    private Socket socket;

    private final static String EVENT = "pcvtmsg";


    public void startClient(String userId){
        try {
            this.userId = userId;
            this.token = "token0000"+userId;
            String query = "userId=" + userId +"&token=" + token +"&park="+ park ;

            IO.Options options = IO.Options.builder().setQuery(query).build();
            Socket socket = IO.socket(url, options);  // 连接到服务器

            //
            socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    log.info("Connected->> userId: {} --------", userId);
                }
            });

            //断开链接
            socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    log.info("Disconnect->> userId: {} *********", userId);
                }
            });


            // 监听自定义事件
            socket.on(EVENT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    log.info("Received->> userId: {};  msg: {}", userId, args[0]);
                }
            });

            // 连接到服务器
            socket.connect();
            TimeUnit.MILLISECONDS.sleep(RandomUtil.randomInt(200, 300));
            this.socket = socket;

        }catch(URISyntaxException e) {
           log.error("connect nezha exception", e);
        } catch (InterruptedException e) {
            log.error("connect nezha exception2", e);
        }
    }


    //切换摄像头  ALL 表示全部摄像头
    public void sendSwitchCamera(String cameras){
        PCSwitchCameraMessage pcSwitchCameraMessage = new PCSwitchCameraMessage();
        pcSwitchCameraMessage.setCameraCodes(cameras);
        this.socket.emit(EVENT, JSON.toJSONString(pcSwitchCameraMessage));
        log.info("SwitchCamera-send-msg->> userId {}, swtich cameras: {}", this.userId, cameras);
    }

    public void colse(){
        this.socket.close();
        log.info("Close->> userId {}", this.userId);
    }




}
